<?php
/**
 * Created by PhpStorm.
 * User: 虚空之翼
 * Date: 2016/11/28
 * Time: 上午10:34
 */

namespace app\admin\controller;

use app\admin\model\Version;
use Chumper\Zipper\Zipper;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;

class Update extends Admin
{
    public function index() {
        // 当前分支
        $branch = @file_get_contents(ROOT_PATH.'.git/HEAD');
        if (!empty($branch)) {
            $branch = trim($branch);
            $i      = strripos($branch, '/');
            $branch = substr($branch, $i + 1);
        }
        $this->assign('branch', $branch);
        // 最新git版本号
        exec("git rev-parse HEAD", $header);
        $this->assign('header', $header);

        $list = Version::order('id desc')->paginate();
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 初始化版本
     */
    public function createVersion() {
        // 最新版
        exec("git rev-parse HEAD", $header);
        // 最近
        $version = Version::order('id desc')->find();
        if ($version) {
            if ($header[0] != $version['git_version']) {
                exec('git diff '.$header[0].' '.$version['git_version'].' --stat', $branch);
                $list = [];
                foreach ($branch as $value) {
                    $files = explode('|', $value);
                    $list[] = trim($files[0]);
                }
                array_pop($list);   // 删除最后一个元素

                // 生成补丁包
                $zipper = new Zipper();
                $name = 'path_'.date('Ymd_').($version['version'] + 1).'.zip';
                $pathName = 'path/'.$name;
                foreach ($list as $value) {
                    $dir = '';
                    $dirData = explode('/', $value);
                    if (count($dirData) > 1) {
                        $dir = substr($value, 0, -mb_strlen($dirData[count($dirData)-1])-1);
                    }
                    if (file_exists(ROOT_PATH.$value)) {
                        $zipper->make($pathName)->folder($dir)->add(ROOT_PATH.$value);
                        $zipper->close();
                    }
                }

                $result = Version::create([
                    'version' => $version['version'] + 1,
                    'git_version' => $header[0],
                    'diff_files' => json_encode($list),
                    'path' => $pathName,
                    'name' => $name
                ]);
                if ($result) {
                    $this->success('创建成功');
                }
            } else {
                $this->error('已经是最新的补丁包');
            }
        } else {
            $result = Version::create([
                'version' => 1,
                'git_version' => $header[0]
            ]);
            if ($result) {
                $this->success('创建成功');
            }
        }
    }

    public function del() {
        $version = Version::get(input('id'));
        $last = Version::order('id desc')->find();
        if ($version->id == $last->id) {
            if(Version::destroy(input('id'))){
                $this->success('删除成功');
            } else {
                $this->error('删除失败！');
            }
        } else {
            $this->error('只能删除最后一条数据');
        }
    }


    public function update() {

        return $this->fetch();
    }

    // 获取最新版本号
    public function getLastVersion() {
        $version = input('version', 1);
        $result = Version::where('version', '>', $version)->order('id')->select();
        if ($result) {
            foreach ($result as $value) {
                unset($value['diff_files']);
            }
            return json(['code'=>1,'msg'=>'版本列表','data'=>$result]);
        } else {
            return json(['code'=>0,'msg'=>'已经是最新版']);
        }
    }

    public function download() {
        $version = Version::get(input('version'));
        if (empty($version)) {
            $this->error('补丁文件不存在');
        }
        // 下载补丁文件
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $version['path']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 200);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $temp = curl_exec($ch);
        $file = '../runtime/temp.zip';
        if(@file_put_contents($file, $temp) && !curl_error($ch)) {
            // 清理目录
            $adapter = new Local(RUNTIME_PATH);
            $filesystem = new Filesystem($adapter);
            $filesystem->deleteDir('path');
            $filesystem->deleteDir('back');

            // 解压补丁，解压插件BUG需要先创建目录
            $tempDir = '../runtime/path';
            if (!is_dir($tempDir)) {
                mkdir($tempDir);
            }
            $zipper = new Zipper();
            $zipper->make($file)->extractTo($tempDir);
            unlink($file);

            $this->updateFiles($tempDir);
            $this->success('更新成功');
        } else {
            $this->error('文件下载失败');
        }
    }

    protected function updateFiles($dir) {
        if(is_dir($dir)) {
            if ($dh = opendir($dir)) {
                $adapter = new Local(ROOT_PATH);
                $filesystem = new Filesystem($adapter);
                while (($file = readdir($dh)) !== false) {
                    if((is_dir($dir."/".$file)) && $file!="." && $file!="..") {
                        $this->updateFiles($dir."/".$file);
                    } else {
                        if($file!="." && $file!=".." && substr($file, 0, 1)!='.') {
                            $file = $dir."/".$file;
                            $target = substr($file, 15);
                            // 备份
                            $filesystem->copy($target, 'runtime/back/'.$target);
                            // 更新
//                            $filesystem->copy('public/'.$file, $target);
                        }
                    }
                }
                closedir($dh);
            }
        }
    }

}